# -*- coding:utf-8 -*-
from application import app
from flask import request, g, redirect
from common.models.admin.erp_user import ErpUser
from common.models.admin.erp_role import ErpRole
from common.libs.admin.UserService import UserService
from common.libs.UrlManager import UrlManager
from common.libs.LogService import LogService
from common.libs.Helper import ops_render

import re


@app.before_request
def before_request():
    ignore_urls = app.config['IGNORE_URLS']
    ignore_check_login_urls = app.config['IGNORE_CHECK_LOGIN_URLS']
    path = request.path

    if '/' == path:
        return

    # 如果是静态文件就不要查询用户信息了
    pattern = re.compile('%s' % "|".join(ignore_check_login_urls))
    if pattern.match(path):
        return

    if '/api' in path:
        return

    # 把登陆信息放到全局变量里面
    user_info = check_login()
    g.current_user = None
    if user_info:
        g.current_user = user_info

    # 得到用户角色
    role_info = check_role()
    g.current_role = None
    if role_info:
        g.current_role = role_info

    # 加入日志
    LogService.addAccessLog()
    pattern = re.compile('%s' % "|".join(ignore_urls))
    if pattern.match(path):
        return

    if not user_info:  # 没有登陆直接跳转到登陆页面
        return redirect(UrlManager.buildUrl("/"))

    if not role_info:  # 没有分配权限直接跳转到登陆页面
        return redirect(UrlManager.buildUrl("/"))

    return


'''
判断用户是否已经登录
'''


def check_login():
    cookies = request.cookies
    auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']] if app.config['AUTH_COOKIE_NAME'] in cookies else None

    if '/api' in request.path:
        app.logger.info(request.path)
        auth_cookie = request.headers.get("Authorization")
        app.logger.info(request.headers.get("Authorization"))

    if auth_cookie is None:
        return False

    auth_info = auth_cookie.split("#")
    if len(auth_info) != 2:
        return False

    try:
        user_info = ErpUser.query.filter_by(uid=auth_info[1]).first()
    except Exception:
        return False

    if user_info is None:
        return False

    if auth_info[0] != UserService.geneAuthCode(user_info):
        return False

    if user_info.status != 1:
        return False

    return user_info


'''
得到当前用户的角色
'''


def check_role():
    user_info = g.current_user
    if not user_info:
        return False

    try:
        role_info = ErpRole.query.filter_by(id=user_info.rid).first()
    except Exception:
        return False

    if role_info is None:
        return False

    if role_info.status != 1:
        return False

    return role_info
